package controllers

import (
	"my-yipuku/db"
	"my-yipuku/models"
	"my-yipuku/utils"

	"github.com/gin-gonic/gin"
)

// 定义个UserController空结构体
type UserController struct{}

/**
 * 查询用信息
 */
func (u UserController) Info(c *gin.Context) {
	user, _ := c.Get("user")
	userObj := user.(*utils.MyClaim)
	info := models.UserByKEY("id", userObj.ID)
	if info.ID != 0 {
		ReturnSuccess(c, 200, "请求成功", info)
	} else {
		ReturnError(c, -200, "用户不存在")
	}
}

/**
 * 个人信息更新
 */
func (u UserController) UpdateMyInfo(c *gin.Context) {
	user, _ := c.Get("user")
	userType := user.(*utils.MyClaim)
	nickname := c.PostForm("nickname")                     // 用户昵称
	password := c.PostForm("password")                     // 密码
	oldPassword := StringToMd5(c.PostForm("old_password")) // 旧密码
	var User models.User
	db.Db.Where("id = ?", userType.ID).First(&User)
	User.Nickname = nickname
	if password != "" {
		if User.Password == oldPassword {
			User.Password = StringToMd5(password)
		} else {
			ReturnError(c, -200, "旧密码错误,请重新输入")
			return
		}
	}
	db.Db.Save(&User)
	ReturnSuccess(c, 200, "更新成功", "")
}
